use "dta\LCD_v13.dta" , clear

* Sum across all parties to assert that we have only one mayor
egen sum_mayor_loc=sum(mayor_loc), by(knr_loc year)

* Create a variable equal to one if party has mayor_loc
egen party_mayor=max(mayor_loc), by(knr_loc partyname_loc year)

* Keep one candidate per list and only observations 2003-2019
keep if rank_loc==1 & year>2000 & year<2020
drop if incomplete_municipality_year==1

* Sort the data by year knr_loc and party_votes_loc in descending order
gsort year knr_loc - party_votes_loc

* Generate a partyrank variable within each year and knr_loc
bysort year knr_loc: gen partyrank = _n

* Drop all party sizes without any mayors
bysort partyrank: tab party_mayor
drop if partyrank>6

* Create a graph
graph bar mayor_loc, ytitle(Fraction) over(partyrank, relabel(1 "Largest" 2 "2nd largest" 3 "3rd largest" 4 "4th largest" 5 "5th largest" 6 "6th largest")) title(Lists with mayor by local party size) ylabel(0(0.2)1.0) scheme(plotplain)
graph save figures/gph/MayorByPartySize.gph, replace


use "dta\LCD_v13.dta" , clear

keep if mayor_loc==1 & year>2000

* Collapse all rank 4 into one category
replace rank_loc=10 if rank_loc>10
tab rank_loc

hist rank_loc, ytitle(Fraction) discrete xlabel(1 "Rank 1" 2 "Rank 2" 3 "Rank 3" 4 "Rank 4" 5 "Rank 5" 6 "Rank 6" 7 "Rank 7" 8 "Rank 8" 9 "Rank 9" 10 "Rank 10+") xtitle("") title(Party list rank among mayors) barwidth(0.8) scheme(plotplain) xlabel(,nogrid)
graph save figures/gph/Rank.gph, replace

cd figures/gph/
graph combine MayorByPartySize.gph Rank.gph, cols(1) ycommon scheme(plotplain)
graph export ../FigureA1.pdf, replace
cd ../../